package org.jeecg.modules.car.web;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.ForeignResult;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.RedisKeyConstant;
import org.jeecg.entity.car.CarInfo;
import org.jeecg.lock.client.RedissonLockClient;
import org.jeecg.modules.car.service.ICarInfoService;
import org.jeecg.modules.car.service.ICarParkingRecordService;
import org.jeecg.modules.car.service.impl.ForeignCarJGSService;
import org.jeecg.vo.car.ForeignCarMonthlyRentReq;
import org.jeecg.vo.car.ForeignCarParkingRecord;
import org.jeecg.vo.car.ForeignCarIotPayTempReq;
import org.jeecg.vo.car.ForeignCarTempCostResp;
import org.redisson.api.RLock;
import org.jeecg.vo.car.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api(tags="外部车禁系统")
@RestController
@RequestMapping("/b/foreign/iot")
public class ForeignCarIoTController {

    @Autowired
    private ForeignCarJGSService foreignCarJGSService;
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private ICarParkingRecordService recordService;

    private final static String appKey = "yktcxyunnetcn";

    @Autowired
    private RedissonLockClient lockClient;

    @AutoLog(value = "测试分布式锁")
    @ApiOperation(value="测试分布式锁", notes="测试分布式锁")
    @PostMapping(value = "/testLock")
    public void testLock(String lockKey){
        RLock rLock = lockClient.getLock(RedisKeyConstant.METER_ORDER_KEY + lockKey);
        boolean getLock = false;
        try {
            if (getLock = lockClient.tryLock(RedisKeyConstant.METER_ORDER_KEY + lockKey,0,20)){
                log.info("加锁成功");
                Thread.sleep(20000);
            }else {
                log.info("加锁失败");
            }
        }catch (Exception e){
            log.error("Redisson 获取分布式锁异常,异常信息:{}",e);
        }finally {
//            rLock.unlock();
        }
    }

    @AutoLog(value = "获取车场车类信息")
    @ApiOperation(value="获取车场车类信息", notes="获取车场车类信息")
    @GetMapping(value = "/getParkCarType")
    public Result getParkCarType(String parkId , HttpServletRequest req) {
        return  foreignCarJGSService.getParkCarType(parkId);
    }

    @AutoLog(value = "获取车场车型信息")
    @ApiOperation(value="获取车场车型信息", notes="获取车场车型信息")
    @GetMapping(value = "/getParkCarModel")
    public Result getParkCarModel(String parkId , HttpServletRequest req) {
        return foreignCarJGSService.getParkCarModel(parkId);
    }

    @AutoLog(value = "获取通道列表")
    @ApiOperation(value="获取通道列表", notes="获取通道列表")
    @GetMapping(value = "/getParkGate")
    public Result getParkGate(String parkId , HttpServletRequest req) {
        return foreignCarJGSService.getParkGate(parkId);
    }

    @AutoLog(value = "有牌车通道口扫码缴费")
    @ApiOperation(value="有牌车通道口扫码缴费", notes="有牌车通道口扫码缴费")
    @GetMapping(value = "/noPlateQRcode")
    public Result<ForeignCarTempCostResp> noPlateQRcode(String parkId,String gateId){
        String openId = org.jeecg.common.util.StringUtils.createSn("code", 3);
        return foreignCarJGSService.noPlateQRcode(parkId,gateId,openId);
    }


    @AutoLog(value = "获取车场车型信息")
    @ApiOperation(value="获取车场车型信息", notes="获取车场车型信息")
    @GetMapping(value = "/saveMonthlyRent")
    public Result saveMonthlyRent(ForeignCarMonthlyRentReq rentReq , HttpServletRequest req) {

        return foreignCarJGSService.saveMonthlyRent(rentReq);
    }

    @AutoLog(value = "获取临停缴费接口")
    @ApiOperation(value="获取临停缴费接口", notes="获取临停缴费接口")
    @GetMapping(value = "/calculatingTempCost")
    public Result<ForeignCarTempCostResp> calculatingTempCost(String recordId, String parkingId, String carNo){
        return foreignCarJGSService.calculatingTempCost(recordId,parkingId,carNo);
    }

    @AutoLog(value = "临停支付通知接口")
    @ApiOperation(value="临停支付通知接口", notes="临停支付通知接口")
    @GetMapping(value = "/payTempCost")
    public Result payTempCost(ForeignCarIotPayTempReq foreignCarPayTempReq){
        return foreignCarJGSService.payTempCost(foreignCarPayTempReq);
    }

    /**
     * 接收 - 车场记录推送
     * @return
     */
    @PostMapping(value = "/pushParkingRecord")
    public ForeignResult pushParkingRecord(@RequestBody ForeignCarParkingRecord record){
        try{
            log.info("车场记录推送接到的数据pushParkingRecord:{}",record);
//            if (StringUtils.isBlank(record.getApp_key())){
//                return ForeignResult.error("appKey不可为空");
//            }
//            //校验appKey
//            if (!MD5Utils.getMd5(appKey).toLowerCase().equals(MD5Utils.getMd5(record.getApp_key()).toLowerCase())){
//                return ForeignResult.error("appKey参数不对！");
//            }
           return foreignCarJGSService.pushParkingRecord(record);
        }catch (Exception e){
            log.error("车场记录推送处理异常:{}",e);
            return ForeignResult.error("处理异常");
        }
    }

    /**
     * 接收 车场未确定订单推送数据
     * @param record
     * @return
     */
    @PostMapping(value = "/pushCarWithoutPayRecord")
    public ForeignResult pushCarWithoutPayRecord(@RequestBody ForeignWithoutPayRecord record){
        try {
            log.info("车场未确定订单推送数据:{}",record);
            return foreignCarJGSService.pushCarWithoutPayRecord(record);
        }catch (Exception e){
            log.error("车场未确定订单推送数据异常：{}", e);
            return ForeignResult.error("未确定订单推送数据异常");
        }
    }

    /**
     * 接收 车场线下缴费记录推送
     * @param record
     * @return
     */
    @PostMapping(value = "/pushCarOfflinePayRecord")
    public ForeignResult pushCarOfflinePayRecord(@RequestBody ForeignCarOfflinePayRecord record){
        try {
            log.info("车场线下缴费记录推送数据pushCarOfflinePayRecord:{}",record);
            /*if (StringUtils.isBlank(record.getApp_key())){
                return ForeignResult.error("appKey不可为空");
            }
            //校验appKey
            if (!MD5Utils.getMd5(appKey).toLowerCase().equals(MD5Utils.getMd5(record.getApp_key()).toLowerCase())){
                return ForeignResult.error("appKey参数不对！");
            }*/
            if (null == record.getOnlyCode() || !record.getPayType().contains("现金")){
                log.warn("支付方式非现金，数据丢弃：{}",record);
                return ForeignResult.ok();
            }
            return foreignCarJGSService.pushCarOfflinePayRecord(record);
        }catch (Exception e){
            log.error("车场线下缴费记录推送异常：{}", e);
            return ForeignResult.error("缴费记录推送异常");
        }
    }

    @ApiOperation(value="手动补全-车辆在场状态")
    @GetMapping(value = "/patchIsExit")
    public Result patchIsExit(String parkId){
        log.info("手动补全-车辆在场状态:{}",parkId);
        List<CarInfo> carInfoList = carInfoService.findByParkId(parkId);
        int count = 0;
        long startTime = System.currentTimeMillis();
        for (CarInfo car:carInfoList){
            if (car.getIsExit() != null) continue;
            Integer isExit = recordService.getIsExitByPlate(car.getCarNo());
            if (isExit != null){
                carInfoService.updateIsExist(car.getId(),car.getTenantId(),isExit);
                count++;
            }
        }
        long endTime = System.currentTimeMillis();
        return Result.ok("处理结束共计:"+count+",耗时:" + (endTime-startTime)/1000 + "s");
    }
}
